import sys
sys.path.append("./test_case")
sys.path.append("./test_case/models")
sys.path.append("./email")
sys.path.append("./icon")
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication,QHBoxLayout, QVBoxLayout,QPushButton, QComboBox,QInputDialog,QLabel,QLineEdit
from PyQt5.QtCore import *
from run_test import test
from send_mail import send_email
from selenium import webdriver
from PyQt5.QtGui import QIcon
import re
import unittest
from models.myunit import MyTest
from test_case.shopping_sta import shoppingTest
from test_case.login_sta import loginTest
testcase = []
thread_number = 1
report = 1
driver = 'IE'
class Example(QWidget):

    def __init__(self,parent):
        QWidget.__init__(self)
        self.parent = parent
        self.initUI()
    def load_txt(self):
        # 读取代码
        fr = open('testcase.txt', 'r')
        dic = {}
        keys = []  # 用来存储读取的顺序
        for line in fr:
            v = line.strip().split(':')
            dic[v[0]] = v[1]
            keys.append(v[0])
        fr.close()
        # print(dic)
        return dic
    def search_testcase(self):
        testcase = unittest.defaultTestLoader.discover('./test_case', pattern='*_sta.py')
        testcase_numbers = re.findall(r'(test_[^<>]*)', str(testcase))
        return testcase_numbers


    def initUI(self):
        testcase_numbers = self.search_testcase()
        names = locals()
        hbox = QVBoxLayout()
        key_list = []
        value_list = []
        mydisc = self.load_txt()
        for key, value in mydisc.items():
            key_list.append(key)
            value_list.append(value)
        for i in range(0, len(testcase_numbers)):
            names['x%s' % i] = testcase_numbers[i]
            testcase_name = names['x%s' % i]
            if testcase_name in value_list:
                get_value_index = value_list.index(testcase_name)
                # print("你要查询的值对应的键为："+key_list[get_value_index])
                testcase_name = key_list[get_value_index]
            else:
                print("你要查询的值"+testcase_name+"不存在" )
            names['x%s' % i] = QCheckBox(testcase_name, self)
            names['x%s' % i].stateChanged.connect(self.addTest)
            hbox.addWidget(names['x%s' % i])
        hbox.addStretch(1)
        vbox = QHBoxLayout()
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.setWindowTitle('质量管理系统自动化测试')
        self.show()

    def addTest(self, state):
        checkBox = self.sender()
        key_list = []
        value_list = []
        mydisc = self.load_txt()
        for key, value in mydisc.items():
            key_list.append(key)
            value_list.append(value)
        if state == Qt.Checked:
            if checkBox.text() in key_list:
                get_value_index = key_list.index(checkBox.text())
                testcase_name = value_list[get_value_index]
                testcase.append(testcase_name)
                print("已选："+checkBox.text())
            else:
                print("你要查询的值:"+checkBox.text()+"不存在")
        else:
            if checkBox.text() in key_list:
                get_value_index = key_list.index(checkBox.text())
                testcase_name = value_list[get_value_index]
                testcase.remove(testcase_name)
                print("取消了："+checkBox.text()+"的选中")
            else:
                print("你要查询的值:"+checkBox.text()+"不存在"  )


class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        tabs = QtWidgets.QTabWidget(self)
        tab1 = QtWidgets.QWidget()
        console = Example(self)
        console.setMinimumSize(800, 3000)
        scroll = QtWidgets.QScrollArea()
        scroll.setWidget(console)
        scroll.setAutoFillBackground(True)
        scroll.setWidgetResizable(True)
        combo = QComboBox(self)
        combo.addItem("1")
        combo.addItem("2")
        combo.addItem("3")
        combo.addItem("4")
        combo.activated[str].connect(self.onActivated)
        report = QComboBox(self)
        report.addItem("是")
        report.addItem("否")
        report.activated[str].connect(self.onReport)
        driver = QComboBox(self)
        driver.addItem("IE")
        driver.addItem("Firefox")
        driver.addItem("Chrome")
        driver.activated[str].connect(self.ondriver)
        btn1 = QPushButton("运行所选的用例", self)
        btn1.setIcon(QIcon('./icon/run.png'))
        btn1.setIconSize(QSize(30, 30))
        btn2 = QPushButton("运行所有的用例", self)
        btn2.setIcon(QIcon('./icon/run.png'))
        btn2.setIconSize(QSize(30, 30))
        btn3 = QPushButton("清空所选的用例", self)
        btn3.setIcon(QIcon('./icon/delete.png'))
        btn3.setIconSize(QSize(30, 30))
        btn4 = QPushButton("发送测试的报告", self)
        btn4.setIcon(QIcon('./icon/email.png'))
        btn4.setIconSize(QSize(30, 30))
        hbox2 = QVBoxLayout()
        hbox4 = QHBoxLayout()
        hbox5 = QHBoxLayout()
        hbox6 = QHBoxLayout()
        lable6 = QLabel("多线程数:")
        lable7 = QLabel("生成测试报告:")
        lable8 = QLabel("浏览器:")
        hbox4.addWidget(lable6)
        hbox4.addWidget(combo)
        hbox5.addWidget(lable7)
        hbox5.addWidget(report)
        hbox6.addWidget(lable8)
        hbox6.addWidget(driver)
        hbox2.addLayout(hbox4)
        hbox2.addLayout(hbox5)
        hbox2.addLayout(hbox6)
        hbox2.addWidget(btn4)
        hbox2.addWidget(btn1)
        hbox2.addWidget(btn3)
        hbox2.addWidget(btn2)
        hbox2.addStretch(1)
        btn1.clicked.connect(self.buttonClicked)
        btn2.clicked.connect(self.buttonClicked2)
        btn3.clicked.connect(self.buttonClicked3)
        btn4.clicked.connect(self.buttonClicked4)
        vbox = QHBoxLayout()
        vbox.addWidget(scroll)
        vbox.addLayout(hbox2)
        tab1.setLayout(vbox)
        #账号密码标签页
        tab2 = QtWidgets.QWidget()
        lb1 = QLabel(u'账户：')
        lb2 = QLabel(u'密码：')
        lb3 = QLabel(u'发件邮箱地址：')
        lb4 = QLabel(u'邮箱密码：')
        lb5 = QLabel(u'邮箱建议使用新浪邮箱，其他邮箱有可能无法发送！')
        lb6 = QLabel(u'商品1：')
        lb7 = QLabel(u'商品2：')
        lb8 = QLabel(u'商品3：')
        lb9 = QLabel(u'商品4：')
        self.userEntry = QLineEdit()
        self.passEntry = QLineEdit()
        self.passEntry.setEchoMode(QLineEdit.Password)
        self.MailEntry = QLineEdit()
        self.MailpassEntry = QLineEdit()
        self.MailpassEntry.setEchoMode(QLineEdit.Password)
        self.commodity1 = QLineEdit()
        self.commodity2 = QLineEdit()
        self.commodity3 = QLineEdit()
        self.commodity4 = QLineEdit()
        self.userEntry.setText('sd452555563')
        self.passEntry.setText('naruto20111992')
        hbox6 = QHBoxLayout()
        hbox6.addWidget(lb1)
        hbox6.addWidget(self.userEntry)
        hbox7 = QHBoxLayout()
        hbox7.addWidget(lb2)
        hbox7.addWidget(self.passEntry)
        hbox8 = QHBoxLayout()
        hbox8.addWidget(lb3)
        hbox8.addWidget(self.MailEntry)
        hbox9 = QHBoxLayout()
        hbox9.addWidget(lb4)
        hbox9.addWidget(self.MailpassEntry)
        hbox10 = QHBoxLayout()
        hbox10.addWidget(lb6)
        hbox10.addWidget(lb7)
        hbox10.addWidget(lb8)
        hbox10.addWidget(lb9)
        hbox11 = QHBoxLayout()
        hbox11.addWidget(self.commodity1)
        hbox11.addWidget(self.commodity2)
        hbox11.addWidget(self.commodity3)
        hbox11.addWidget(self.commodity4)

        vbox2 = QVBoxLayout()
        vbox2.addLayout(hbox6)
        vbox2.addLayout(hbox7)
        vbox2.addWidget(lb5)
        vbox2.addLayout(hbox8)
        vbox2.addLayout(hbox9)
        vbox2.addLayout(hbox10)
        vbox2.addLayout(hbox11)

        vbox2.addStretch(1)
        tab2.setLayout(vbox2)
        tabs.addTab(tab1, u"测试用例")
        tabs.addTab(tab2, u"账号密码")
        tabs.resize(500, 550)
        self.resize(500, 550)
        # 禁止最大化
        # self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
        self.setWindowTitle('自动化测试工具')
        self.setWindowIcon(QIcon('./icon/logo.png'))
        self.show()

    def onActivated(self, text):
        global thread_number
        if text == '1':
            thread_number = 1
        elif text == '2':
            thread_number = 2
        elif text == '3':
            thread_number = 3
        elif text == '4':
            thread_number = 4
    def onReport(self, text):
        global report
        if text == '是':
            report = 1
        elif text == '否':
            report = 0
    def ondriver(self, text):
        global driver
        if text == 'IE':
            driver = 'IE'
        elif text == 'Firefox':
            driver = 'Firefox'
        elif text == 'Chrome':
            driver = 'Chrome'

    def buttonClicked(self):#运行所选的测试用例
        # print(report)
        shoppingTest.username = self.userEntry.text()
        shoppingTest.password = self.passEntry.text()
        loginTest.username = self.userEntry.text()
        loginTest.password = self.passEntry.text()
        shoppingTest.commodity_name1 = self.commodity1.text()
        shoppingTest.commodity_name2 = self.commodity2.text()
        shoppingTest.commodity_name3 = self.commodity3.text()
        shoppingTest.commodity_name4 = self.commodity4.text()
        MyTest.driver = driver
        test(testcase,thread_number,report)

    def buttonClicked2(self):#运行所有的测试用例
        case = unittest.defaultTestLoader.discover('./test_case', pattern='*_sta.py')
        testcase_numbers = re.findall(r'(test_[^<>]*)', str(case))
        names = locals()
        for i in range(0, len(testcase_numbers)):
            c = testcase_numbers[i]
            testcase.append(c)
        print(testcase)
        test(testcase,thread_number,report)

    def buttonClicked3(self):#置空所有测试用例
        testcase = []
        print("已清空所有测试用例")

    def buttonClicked4(self):#发送邮件
        text, ok = QInputDialog.getText(self, '发送最新版本的自动化测试报告',
                                        '请输入要发送的邮箱地址:')
        email_address = self.MailEntry.text()
        email_password = self.MailpassEntry.text()
        if ok:
            send_email(email_address,email_password,text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MainWindow()
    sys.exit(app.exec_())